package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.pojo.*;
import com.qf.service.*;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.02.21
 * @since 1.0
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Autowired
    DtsBrandService brandService;

    @Autowired
    DtsCategoryService categoryService;

    @Autowired
    DtsGoodsAttributeService attributeService;

    @Autowired
    DtsGoodsSpecificationService specificationService;

    @Autowired
    DtsGoodsProductService productService;
    @Override
    public int queryTotal() {

        LambdaQueryWrapper<DtsGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsGoods::getDeleted,false);
        Integer count = goodsMapper.selectCount(wrapper);
        return count;
    }

    @Override
    public IPage<DtsGoods> queryPage(Integer page, Integer limit, String goodsSn, String name, String sort, String order, List<Integer> brandIds) {

        IPage<DtsGoods> iPage = new Page<>(page,limit);

        QueryWrapper wrapper = new QueryWrapper();

        //判断商品编号是否为空
        if(!StringUtils.isEmpty(goodsSn)){
            wrapper.like("goods_sn",goodsSn);
        }
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if(brandIds !=null && brandIds.size() > 0){
            wrapper.in("brand_id",brandIds);
        }
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            if (order.equals("desc")){
                wrapper.orderByDesc(sort);
            }else {
                wrapper.orderByAsc(sort);
            }
        }

        goodsMapper.selectPage(iPage,wrapper);
        return iPage;
    }

    @Override
    public DtsGoods findById(Integer id) {
        return goodsMapper.selectById(id);
    }

    //校验
    public Object validate(GoodsAllinone goodsAllinone){
        if(goodsAllinone == null){
            return ResponseUtil.badArgument();
        }
        //获取商品的对象
        DtsGoods goods = goodsAllinone.getGoods();
        //商品名称
        if(StringUtils.isEmpty(goods.getName())){
            return ResponseUtil.badArgument();
        }
        //商品编号
        if(StringUtils.isEmpty(goods.getGoodsSn())){
            return ResponseUtil.badArgument();
        }

        //获取品牌商id
        Integer brandId = goods.getBrandId();
        if(brandId !=null){
            if(brandService.findById(brandId) == null){
                return ResponseUtil.badArgument();
            }
        }

        //品牌分类
        Integer categoryId = goods.getCategoryId();
        if (categoryId != null){
            if (categoryService.findById(categoryId) == null){
                return ResponseUtil.badArgument();
            }

        }

        //获取商品属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if (attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {

               if (attribute.getAttribute() == null || attribute.getValue() == null){

                   return ResponseUtil.badArgument();
               }
            }
        }

        //获取商品的规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if (specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
              if (specification.getSpecification() == null || specification.getValue() == null){
                  return ResponseUtil.badArgument();

              }
            }
        }

        //获取库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if (products != null && products.length > 0){
            for (DtsGoodsProduct product : products) {
                if (product.getNumber() == null || product.getPrice() == null){
                    return ResponseUtil.badArgument();
                }
            }
        }
        return null;
    }

    @Override
    public Object update(GoodsAllinone goodsAllinone) {
        Object result = this.validate(goodsAllinone);
        if(result !=null){
            return result;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        //更新数据库

        //1、更新商品表
        goods.setUpdateTime(new Date());
        goodsMapper.updateById(goods);

        //2、更新属性表
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        //2.1、删除此商品的所有相关属性
        attributeService.deleteByGoodsId(goods.getId());
        //2.2、添加新的商品属性
        if(attributes != null && attributes.length > 0 ){
            for (DtsGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(false);

                attributeService.insert(attribute);
            }

        }

        //3、更新规格表
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        //3.1、删除此商品的所有规格
        specificationService.deleteByGoodsId(goods.getId());
        //3.2、添加新的商品规格
        if (specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specification.setDeleted(false);

                specificationService.insert(specification);
            }
        }


        //4、更新库存表
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        //4.1、删除此商品的所有库存
        productService.deleteByGoodsId(goods.getId());
        //4.2、添加新的商品库存
        if (products != null && products.length > 0){
            for (DtsGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                product.setDeleted(false);
                productService.insert(product);
            }
        }

        return ResponseUtil.ok();
    }

    @Autowired
    DtsOrderGoodsService orderGoodsService;

    @Override
    public Object deleteById(Integer id) {

        List<DtsOrderGoods> orderGoods = orderGoodsService.findByGoodsId(id);
        //1、判断商品是否被订单关联，如果关联不能删除
       if (orderGoods != null && orderGoods.size() > 0){

           //unsupport 业务不支持
           return ResponseUtil.unsupport();
       }

        //2、删除商品对应的属性
        attributeService.deleteByGoodsId(id);
        //3、删除商品对应的库存
        productService.deleteByGoodsId(id);
        //4、删除商品对应的规格
        specificationService.deleteByGoodsId(id);
        //5、删除商品
        goodsMapper.deleteById(id);

        return ResponseUtil.ok();
    }

    @Override
    public Object create(GoodsAllinone goodsAllinone) {
        //先校验
        Object result = validate(goodsAllinone);
        if(result != null){
            return result;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        //新增商品   goods.id 是新增商品后 会自动回显主键（mybatis-plus）
        goodsMapper.insert(goods);
        //新增商品属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attribute.setDeleted(false);
                attributeService.insert(attribute);
            }
        }
        //新增商品规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specification.setDeleted(false);
                specificationService.insert(specification);
            }
        }

        //新增商品库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if (products != null && products.length > 0){
            for (DtsGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                product.setDeleted(false);
                productService.insert(product);
            }
        }
        return ResponseUtil.ok();
    }
}
